import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Demo_UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp = "";
    private int serverPort = 0;
    public Demo_UdpEchoClient(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = ip;
        this.serverPort = port;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        while(true){
            Scanner scanner = new Scanner(System.in);
            //1.创建UDP数据包并发送
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            //2.等待服务器响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //3.打印响应数据
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        //Demo_UdpEchoClient client = new Demo_UdpEchoClient("42.192.83.143", 9090);
        Demo_UdpEchoClient client = new Demo_UdpEchoClient("127.0.0.1", 9999);
        client.start();
    }
}
